import { ref } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { login } from '../apis/auth'

export function useLogin() {
  const loading = ref(false)
  const router = useRouter()

  const handleLogin = async (formData) => {
    try {
      loading.value = true
      // {code:200,data:"token",message:''}
      const response = await login(formData)
      
      if (response.code === 200) {
        ElMessage.success('登录成功')
        // 存储token到本地存储
        localStorage.setItem('token', response.data)
        // 登录成功后自动跳转到仪表盘
        router.push('/home')
        return { success: true, data: response.data }
      } else {
        ElMessage.error(response.message || '登录失败')
        return { success: false, message: response.message }
      }
    } catch (error) {
      console.error('登录错误:', error)
      ElMessage.error('登录失败，请检查网络连接')
      return { success: false, message: '登录失败，请检查网络连接' }
    } finally {
      loading.value = false
    }
  }

  return {
    loading,
    handleLogin
  }
}